package com.gitee.hermer.engine.jars.dependent.activemq.core;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.DisposableBean;

import com.gitee.hermer.boot.jee.commons.log.UtilsContext;
import com.gitee.hermer.boot.jee.commons.utils.StringUtils;
import com.gitee.hermer.engine.jars.core.domain.EngineConstant;
import com.gitee.hermer.engine.jars.dependent.activemq.core.pool.ActiveMQSessionPoolFactory;
import com.gitee.hermer.engine.jars.dependent.activemq.robin.WeightRoundRobin;


public class ActiveMQManager extends UtilsContext implements DisposableBean{


	private ActiveMQCluster cluster;
	private List<ActiveMQSessionPoolFactory> factory;


	@Override
	public void destroy() throws Exception {
		if(this.factory!= null){
			for (ActiveMQSessionPoolFactory mon : this.factory) {
				mon.destroy();
			}
			this.factory.clear();
		}
	}





	public ActiveMQManager(ActiveMQCluster cluster){
		this.cluster = cluster;
		this.factory = cluster.getFactory();
	}



	public List<ActiveMQSessionPoolFactory> getFactory()
	{
		return cluster.getFactory();
	}


	public boolean monitor()
	{
		for (ActiveMQSessionPoolFactory maFactory : this.factory)
		{
			boolean isOK = maFactory.monitor();
			int state = maFactory.getStatus();
			if (isOK)
			{
				if (state == EngineConstant.INT_NOT_SCUUCED) {
					info("mq 连接由异常已恢复正常,url=" + maFactory.getBrokerURL());
				}
				maFactory.setStatus(EngineConstant.INT_SCUUCED);
			}
			else
			{
				maFactory.setStatus(EngineConstant.INT_NOT_SCUUCED);
				warn("mq 连接由异常,url=" + maFactory.getBrokerURL());
			}
		}
		return true;
	}

	public ActiveMQSessionPoolFactory getMQSessionFacory(String terminalId)
	{
		ActiveMQSessionPoolFactory facotry = null;
		int index = 0;
		if (StringUtils.hasLength(terminalId))
		{
			index = Integer.valueOf(terminalId).intValue() % this.factory.size();
			facotry = this.factory.get(index);
		}
		else
		{
			facotry = WeightRoundRobin.getInstance(this).getMqSessionFactory();
		}
		if ((facotry == null) || 
				(facotry.getStatus() == EngineConstant.INT_NOT_SCUUCED)) {
			facotry = findActiveFacotry();
		}
		return facotry;
	}

	private ActiveMQSessionPoolFactory findActiveFacotry()
	{
		for (ActiveMQSessionPoolFactory mq : this.factory) {
			if (mq.getStatus() == EngineConstant.INT_NOT_SCUUCED) {
				return mq;
			}
		}
		return null;
	}

}
